package com.sangeng.handler;

import com.alibaba.fastjson.JSON;
import com.sangeng.domain.ResponseResult;
import com.sangeng.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LENOVO
 * @version 1.0
 * @date 2025/6/19 22:00
 * 认证过程中出现的异常会被封装成AuthenticationException然后调用
 * AuthenticationEntryPoint对象的方法去进行异常处理
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    /**
     * 认证失败处理
     *
     * 认证过程中出现的异常会被封装成AuthenticationException然后调用
     * AuthenticationEntryPoint对象的方法去进行异常处理
     *
     * @param httpServletRequest 请求
     * @param httpServletResponse 响应
     * @param e 异常
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        // 返回认证失败信息
        ResponseResult result = new ResponseResult(HttpStatus.UNAUTHORIZED.value(), "认证失败请重新登录");
        String json = JSON.toJSONString(result);
        //异常处理,使用工具类返回给前端
        WebUtils.renderString(httpServletResponse , json);
    }
}